package com.lute.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.model.Approver;
import com.lute.model.EmployeeAccountingPeriod;
import com.lute.model.EmployeeAccountingPeriodState;
import com.lute.model.EmployeeProfile;
import com.lute.model.UserEntitlement;
import com.lute.utils.ServerErrorResponse;

@Controller
public class ApproverProfileUpdateServlet {
	
	@RequestMapping (value="/approverProfileUpdate",method= RequestMethod.POST, headers = "Content-type=application/json")
	public @ResponseBody String accountingPeriodChecked(@RequestBody String profileJSON, HttpServletRequest request) throws JSONException {
		String result = "";
		/* example data: only email and note */
		String email;
		String note;
		JSONObject jsonReq;
		JSONObject jsonRes = new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		try {
			jsonReq = new JSONObject(profileJSON);
			email = jsonReq.getString("email");
			note = jsonReq.getString("note");
		} catch(JSONException e) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		
		/* check if json data was not malformed */
		if( (jsonReq.isNull("email")) && (jsonReq.isNull("note")) ) {
			jsonRes.put("result",ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		
		String role = (String)session.getAttribute("role");
		
		/* check  authorization */
		if(!(role.equals("approver"))) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
			result = jsonRes.toString();
			return result;
		}
		
		int sessionUserId = (Integer)session.getAttribute("sessionUserId");
		
		EmployeeProfile approverProfile = EmployeeProfile.getEmployeeProfileByEmployeeIdFromDB("id_user", sessionUserId);
		approverProfile.setEmail(email);
		approverProfile.setNote(note);
		
		/* update approver's profile in DataBase */
		EmployeeProfile.updateEmployeeProfileInDB(approverProfile);
		
		jsonRes.put("result","OK");
		result = jsonRes.toString();
		return result;
	}
}
